//发起请求
const request = (promise, loading = false, config) => {
  return new Promise( (resolve, reject) => {
      // 1. 添加配置验证
      if (!config || !config.api) {
          console.error('SDK配置错误: 缺少API配置');
          wx.showToast({title: "SDK配置错误", icon: 'none'});
          reject(new Error('SDK配置错误'));
          return;
      }
      
      // 2. 获取环境URL
      let baseUrl = '';
      if (config.api[config.env] && config.api[config.env].url) {
          baseUrl = config.api[config.env].url;
      } else if (config.api.url) {
          // 兼容旧版配置
          baseUrl = config.api.url;
      } else {
          console.error('SDK配置错误: 缺少API URL');
          wx.showToast({title: "SDK配置错误", icon: 'none'});
          reject(new Error('SDK配置错误'));
          return;
      }
      
      if (['produce','dev','host'].includes(config.env)) {
          if (loading) {
              wx.showLoading({
                  title:'请求中',
                  mask: true
              })
          }
          
          // 3. 添加请求日志
          console.log(`发起请求: ${baseUrl + promise.url}`, promise.data);
          
          wx.request({
              url: baseUrl + promise.url,  // 使用确定的baseUrl
              method: promise.method || 'GET',
              header: promise.header || (config.api.header || {}),
              data: promise.data,
              success: res => {
                  if (res.statusCode === 200) {
                      resolve(res.data);
                  } else {
                      const errorMsg = res.data?.msg || `请求失败 (${res.statusCode})`;
                      wx.showToast({
                          title: errorMsg,
                          icon: 'none',
                          duration: 2000
                      });
                      reject(errorMsg);
                  }
              },
              fail: err => {
                  wx.showToast({title: "网络异常",icon: 'none'});
                  reject(err);
              },
              complete() {
                  if (loading) {
                      wx.hideLoading();
                  }
              }
          });
      } else {
          wx.showToast({title: "环境异常",icon: 'none'});
          reject({msg: "环境异常"});
      }
  });
};

module.exports = {
  request: request
}